package com.cloud.quickcore.thread;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author NiJo_H
 * @version 1.0
 * @date 2020/1/22 11:45
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class test {
    @Autowired
    private ExecutorService executorService;

    //线程返回结果
    private static List<Object> futureList = new ArrayList<>();

    private static int old = 0;

    /**
     * 制造任务
     */
    @Test
    public void makeTest() throws InterruptedException {
        long startTime=System.currentTimeMillis();
        int index = 0;
        for (int i = 1; i <= 10000; i++) {
            int finalI = i;
            //达到队列容量
            if (i == 21) {
                index = i + this.listDetection();
                System.out.println(index);
            }
            if (i == index) {
                index = i + this.listDetection();
                System.out.println("---下次for断下表:" + index);
            }

            executorService.submit(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    log.info("当前第" + finalI + "个任务放入线程池");
                    return true;
                }
            });
        }
        long endTime=System.currentTimeMillis();
        System.out.println("一共用时:"+(endTime-startTime));

    }

    public synchronized int listDetection() {
        while (true) {
            int s = ((ThreadPoolExecutor) this.executorService).getQueue().size();
            int result = 20-s;
            System.out.println("当前队列:"+s+",下次添加:"+result);
            if (result > 0) {
                return result;
            }
            System.out.println("当前还没有队列可添加");
        }
    }

}
